<script lang="tsx">
import { get, post, message, loadFile } from '@/utils'
import { FormInstance, TableColumnData, FormItem, InputNumber } from '@arco-design/web-vue'
import useTable from '@/hooks/useTable'
import CDrawer from '@/components/common/Drawer.vue'
import useProduct from '@/hooks/useProduct'
export default defineComponent({
  props: {
    show: {
      type: Boolean as PropType<boolean>,
    },
    goodsId: {
      type: String as PropType<string>,
    },
    id: {
      type: String as PropType<string>,
    },
    /**活动ID */
    publicId: {
      required: true,
    },
  },
  emits: ['update:show', 'confirm'],
  setup(props, { emit }) {
    const { formatColumns } = useTable()
    const sellerLevelList = ref<SellerLevel[]>([])
    const formRef = ref<FormInstance>()
    const detail = reactive({
      type: 1,
      countType: 1,
      skuList: [] as any[],
    })
    const { info, getInfo: getGoodsInfo } = useProduct()

    const getSellerLevelList = () => {
      return new Promise(resolve => {
        get({ url: '/server-shop/sys-seller/place/level/list' }, ({ data }) => {
          sellerLevelList.value = data
          resolve({})
        })
      })
    }
    const getGoodsInfo1 = () => {
      detail.skuList = []
      getGoodsInfo(props.goodsId, () => {
        info.value.goodsSkuList.forEach(item => {
          let str = ''
          const specObj = JSON.parse(item.spec)
          const values = Object.values(specObj)
          str = values.join('+')
          const _item = {
            ...item,
            name: str || '默认',
            price: item.goodsPrice,
            price2: item.marketPrice,
            levelList: [],
          }
          console.log('🚀 ~ getGoodsInfo ~ _item:', _item)
          detail.skuList.push(_item)
        })
        console.log(detail)
        getSellerLevelList()
        if (props.id) getInfo()
      })
    }
    onMounted(() => {
      if (props.goodsId) {
        getGoodsInfo1()
      }
    })
    const getInfo = () => {
      get({ url: '/server-shop/sys-seller/pattern/goods/info', data: { id: props.id } }, ({ data }) => {
        console.log(data)
        const _data = JSON.parse(data.config)
        Object.assign(detail, _data)
      })
    }
    const columns = computed(() => {
      const columns = formatColumns([
        {
          title: '规格',
          dataIndex: 'name',
          width: 100,
        },
        {
          title: '销售价',
          width: 100,
          dataIndex: 'price',
        },
        {
          title: '成本价',
          width: 100,
          dataIndex: 'price2',
        },
      ])

      const levelColumns: any = []
      /**处理动态加载的等级配置 */
      sellerLevelList.value.forEach(item => {
        levelColumns.push({
          title: item.name,
          dataIndex: 'level' + item.level,
          width: 500,
          render: ({ record }) => {
            let _index = record.levelList.findIndex(f => f.level == item.level)
            /**-1代表之前没有配置的 */
            if (_index == -1) {
              record.levelList.push({
                level: item.level,
                direct: 0,
                indirect: 0,
              })
              _index = record.levelList.length - 1
            }
            return (
              <a-space>
                <a-form-item label="直销" label-col-props={{ span: 6 }} wrapper-col-props={{ span: 18 }}>
                  <a-input-number
                    style="width:150px"
                    v-model={record.levelList[_index].direct}
                    hide-button
                    max={detail.countType == 2 ? record.price : 100}
                    min={detail.countType == 2 ? 0.01 : 0}
                    v-slots={{
                      append: () => <>{detail.countType == 2 ? '元' : '%'}</>,
                    }}
                  />
                </a-form-item>
                <a-form-item label="分销" label-col-props={{ span: 6 }} wrapper-col-props={{ span: 18 }}>
                  <a-input-number
                    style="width:150px"
                    v-model={record.levelList[_index].indirect}
                    hide-button
                    v-slots={{
                      append: () => <>{detail.countType == 2 ? '元' : '%'}</>,
                    }}
                  />
                </a-form-item>
              </a-space>
            )
          },
        })
      })
      return columns.concat(formatColumns(levelColumns)) as TableColumnData[]
    })
    const submit = done => {
      const query = {
        goodsId: props.goodsId,
        patternId: props.publicId,
        id: props.id || '',
        config: JSON.stringify(detail),
      }
      console.log('🚀 ~ submit ~ query:', query)
      const method = props.id ? 'update' : 'save'
      post(
        { url: '/server-shop/sys-seller/pattern/goods/' + method, data: query },
        ({ code, msg }) => {
          done(code == 200)
          message({
            type: code == 200 ? 'success' : 'error',
            content: msg,
          })
          if (code == 200) {
            emit('update:show', false)
            emit('confirm')
          }
        },
        () => done(false)
      )
    }
    watch(
      () => detail.countType,
      newVal => {
        if (newVal == 2) {
          detail.type = 2
        }
      }
    )
    return () => (
      <CDrawer visible={props.show} width="900px" onUpdate:visible={val => emit('update:show', val)} onBeforeOk={done => submit(done)} mask-closable={false} title="配置商品分销佣金" onCancel={() => emit('update:show', false)}>
        <a-form label-col-props={{ span: 3 }} wrapper-col-props={{ span: 21 }} ref={formRef.value}>
          <a-form-item label="商品名称">{info.value?.name}</a-form-item>
          <a-form-item label="发放方式">
            <a-radio-group
              v-model={detail.countType}
              options={[
                {
                  label: '按固定金额',
                  value: 2,
                },
                {
                  label: '按比例',
                  value: 1,
                },
              ]}
            />
          </a-form-item>
          <a-form-item label="配置方式">
            <a-radio-group
              v-model={detail.type}
              disabled={detail.countType == 2}
              options={[
                {
                  label: '使用默认配置',
                  value: 1,
                },
                {
                  label: '自定义配置',
                  value: 2,
                },
              ]}
            />
          </a-form-item>
          {detail.type == 2 ? (
            <a-form-item label="自定义配置">
              <a-space direction="vertical" style="max-width:100%;">
                <a-table columns={columns.value} sticky-header={0} pagination={false} data={detail.skuList} scroll={{ x: 500, y: 500 }} scrollbar={true} />
                <a-button type="primary" long onClick={() => getGoodsInfo1()}>
                  刷新规格
                </a-button>
              </a-space>
            </a-form-item>
          ) : (
            <></>
          )}
        </a-form>
      </CDrawer>
    )
  },
})
</script>

<style lang="less" scoped></style>
